//
//  HomeButtonsCollectionViewCell.m
//  YYZB
//
//  Created by 顾悦 on 16/3/23.
//
//

#import "HomeButtonsCollectionViewCell.h"

#import "HomeButtonCollectionViewCell.h"

@implementation HomeButton

- (instancetype)initWithDictionary:(NSDictionary *)d {
    HomeButton *item = [self class].new;
    item.icon = d[@"icon"];
    item.name = d[@"name"];
    return item;
}

- (instancetype)initWithIcon:(NSString *)icon name:(NSString *)name selector:(SEL)selector {
    HomeButton *item = [self class].new;
    item.icon = icon;
    item.name = name;
    item.selector = selector;
    return item;
}

@end

@interface HomeButtonsCollectionViewCell () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property(weak, nonatomic) IBOutlet UICollectionView *collectionView;

@end

@implementation HomeButtonsCollectionViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.scrollEnabled = NO;
    [self.collectionView registerNib:[UINib nibWithNibName:@"HomeButtonCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"homeButtonCell"];
}

- (void)setItems:(NSArray<HomeButton *> *)items {
    _items = items;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];
    });}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.items count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeButtonCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homeButtonCell" forIndexPath:indexPath];
    HomeButton *b = self.items[indexPath.item];
    cell.imageView.image = [UIImage imageNamed:b.icon];
    cell.titleLabel.text = b.name;
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize boundsSize = collectionView.bounds.size;
    return CGSizeMake(boundsSize.width / 4, boundsSize.height);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeButton *b = self.items[indexPath.item];
    [self.delegate homeButtonTapped:b];
}

@end
